<script setup lang="tsx">
import { PropType, reactive, ref } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { BaseButton } from '@/components/Button'
import { ElPopconfirm, ElButton, ElTable, ElTableColumn, ElTag } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { useI18n } from '@/hooks/web/useI18n'
import { useValidator } from '@/hooks/web/useValidator'
import { Log } from '@/utils/logError'
import { DictPageResponse } from '@/api/dict/types'
import { getDictDetailApi } from '@/api/dict'
import { cloneDeep } from 'lodash-es'
import DictItemDrawer from '@/views/System/Dict/components/DictItemDrawer.vue'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<DictPageResponse | null>,
    default: () => {}
  }
})

const showDrawer = ref(false)
const itemRow = ref<any>({})
const itemIndex = ref(0)
const itemType = ref<'add' | 'edit'>('add')

const formSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('dict.name'),
    component: 'Input'
  },
  {
    field: 'code',
    label: t('dict.code'),
    component: 'Input'
  },
  {
    field: 'isSystem',
    label: t('dict.isSystem'),
    value: false,
    component: 'Switch'
  },
  {
    field: 'status',
    label: t('department.status'),
    value: true,
    component: 'Switch'
  },
  {
    field: 'description',
    label: t('common.remark'),
    component: 'Input'
  },
  {
    field: 'items',
    label: t('dict.item'),
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => (
          <>
            <BaseButton class="m-t-5px" type="primary" size="small" onClick={() => handleEdit()}>
              {t('dict.addItem')}
            </BaseButton>
            <ElTable data={data.items}>
              <ElTableColumn type="index" prop="id" />
              <ElTableColumn prop="label" label={t('dict.itemName')} />
              <ElTableColumn prop="value" label={t('dict.itemCode')} />
              <ElTableColumn
                prop="status"
                label={t('common.status')}
                v-slots={{
                  default: ({ row }) => {
                    return (
                      <ElTag type={row.status ? 'success' : 'danger'}>
                        {row.status ? t('common.enable') : t('common.disable')}
                      </ElTag>
                    )
                  }
                }}
              />
              <ElTableColumn
                label={t('common.operation')}
                v-slots={{
                  default: ({ row, $index }) => (
                    <>
                      <ElButton size="small" type="primary" onClick={() => handleEdit($index, row)}>
                        编辑
                      </ElButton>
                      <ElPopconfirm
                        title="Are you sure to delete this?"
                        onConfirm={() => handleItemRemove($index)}
                      >
                        {{
                          reference: () => (
                            <ElButton size="small" type="danger">
                              删除
                            </ElButton>
                          )
                        }}
                      </ElPopconfirm>
                    </>
                  )
                }}
              ></ElTableColumn>
            </ElTable>
          </>
        )
      }
    }
  }
])
const rules = reactive({
  name: [required()],
  code: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const handleEdit = (index: number = 0, row: any = null) => {
  const isEdit = !Object.is(row, null)
  itemType.value = isEdit ? 'edit' : 'add'
  itemRow.value = row ? row : {}
  itemIndex.value = index
  showDrawer.value = true
}

const handleItemRemove = async (index: number) => {
  const formData = await getFormData()
  // 删除对应的权限
  await setValues({
    items: formData?.items?.filter((_, idx) => idx !== index)
  })
}

const getDictDetail = async () => {
  try {
    const { code } = props.currentRow || {}
    if (!code) return await setValues({})
    const res = await getDictDetailApi(code)
    await setValues({ ...cloneDeep(props.currentRow), items: res.data })
  } catch (error) {
    Log.error('getDictDetail', error)
  }
}
getDictDetail()

const confirm = async (data: any) => {
  const formData = await getFormData()
  if (itemType.value === 'add')
    return await setValues({
      items: [...(formData?.items || []), data]
    })
  formData.items[itemIndex.value] = data
  await setValues(formData)
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (Array.isArray(formData.parentDeptId) && formData.parentDeptId.length >= 1)
      formData.parentDeptId = formData.parentDeptId[formData.parentDeptId.length - 1]
    else delete formData.parentDeptId
    return formData
  }
}

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" :is-col="false" @register="formRegister" :schema="formSchema" />
  <DictItemDrawer v-model="showDrawer" @confirm="confirm" :type="itemType" :row="itemRow" />
</template>
